#include "registerdialog.h"
#include "ui_registerdialog.h"
#include "global.h"
#include "httpmgr.h"

RegisterDialog::RegisterDialog(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::RegisterDialog)
{
    ui->setupUi(this);

    ui->passwordLineEdit->setEchoMode(QLineEdit::Password);
    ui->password2LineEdit->setEchoMode(QLineEdit::Password);

    // 刷新提示标签Qss状态显示
    ui->errorTip->setProperty("state", "normal");
    repolish(ui->errorTip);

    // 初始化请回回调函数
    initHttpHandlers();

    // 连接Http请求的回调函数
    connect(HttpMgr::GetInstance().get(), &HttpMgr::SignalRegModFinish,
            this, &RegisterDialog::SlotRegModFinish);


}

RegisterDialog::~RegisterDialog()
{
    delete ui;
}

void RegisterDialog::showTip(QString str, bool b_ok)
{
    // 调整显示状态状态
    ui->errorTip->setProperty("state", "normal");
    if (!b_ok) {
        ui->errorTip->setProperty("state", "error");
    }

    ui->errorTip->setText(str);
    repolish(ui->errorTip);
}

void RegisterDialog::initHttpHandlers()
{
    _handlers.insert(ReqId::ID_GET_VARIFY_CODE, [this](const QJsonObject& jsonObj){
        int error = jsonObj["error"].toInt();
        qDebug() << "error: " << error;
        if (error != ErrorCodes::SUCCESS) {
            showTip(tr("参数错误!!!"), false);
            return;
        }

        auto email = jsonObj["email"].toString();
        showTip(tr("验证码已经发送到邮箱"), true);
        qDebug() << "email: " << email;
    });
}

void RegisterDialog::on_varifyBtn_clicked()
{
    auto email = ui->emailLineEdit->text();

    QRegularExpression regex(R"((\w+)(\.|_)?(\w*)@(\w+)(\.(\w+))+)");
    bool match = regex.match(email).hasMatch();
    if (!match) {
        showTip(tr("邮箱地址不正确！！！"), false);
    }

    QJsonObject json_obj;
    json_obj["email"] = email;
    HttpMgr::GetInstance()->PostHttpReq(QUrl(gate_url_prefix + "/get_varifycode"),
                                        json_obj, ReqId::ID_GET_VARIFY_CODE, Modules::REGISTERMOD);
}

void RegisterDialog::SlotRegModFinish(ReqId id, QString res, ErrorCodes err)
{
    if(err != ErrorCodes::SUCCESS) {
        showTip(tr("网络请求错误！！！"), false);
        return;
    }

    // 解析请求结果
    QJsonDocument jsonDoc = QJsonDocument::fromJson(res.toUtf8());
    if (jsonDoc.isNull()) {
        showTip(tr("Json解析失败！！！"), false);
        return;
    }

    // Json解析错误
    if (!jsonDoc.isObject()) {
        showTip(tr("Json解析失败！！！"), false);
        return;
    }
    qDebug() << res;

    // Json解析成功， 调用handlers里根据reqid的处理函数
    _handlers[id](jsonDoc.object());
}




















